//
//  RefreshView.m
//  Category
//
//  Created by Burn on 2020/1/7.
//  Copyright © 2020 menksoft. All rights reserved.
//

#import "RefreshView.h"
#import "UIView+Extension.h"
#import "RefreshConst.h"
@interface RefreshView ()

@property (strong, nonatomic) UIPanGestureRecognizer *pan;

@end


@implementation RefreshView

- (void)willMoveToSuperview:(UIView *)newSuperview{
    [super willMoveToSuperview:newSuperview];
    
    // 旧的父控件移除监听
    [self removeObservers];
    
    if (newSuperview) {
        
        self.state = RefreshIdle;
        
        // 设置宽度
        self.width = newSuperview.width;
        // 设置位置
        self.x = 0;
        self.height = MKRefreshContentInsetSpacing;
        
        // 记录UIScrollView
        _scrollView = (UIScrollView *)newSuperview;
        // 记录UIScrollView最开始的contentInset
        _scrollViewOriginalInset = _scrollView.contentInset;

        //  添加观察
        [self addObservers];
    }
}



- (void)addObservers
{
    NSKeyValueObservingOptions options = NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld;
    [self.scrollView addObserver:self forKeyPath:MKRefreshKeyPathContentOffset options:options context:nil];
    [self.scrollView addObserver:self forKeyPath:MKRefreshKeyPathContentSize options:options context:nil];
    self.pan = self.scrollView.panGestureRecognizer;
    [self.pan addObserver:self forKeyPath:MKRefreshKeyPathPanState options:options context:nil];
}

- (void)removeObservers
{
    [self.superview removeObserver:self forKeyPath:MKRefreshKeyPathContentOffset];
    [self.superview removeObserver:self forKeyPath:MKRefreshKeyPathContentSize];
    [self.pan removeObserver:self forKeyPath:MKRefreshKeyPathPanState];
    self.pan = nil;
}



- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    
    // 遇到这些情况就直接返回
    if (!self.userInteractionEnabled) return;
    
    // 这个就算看不见也需要处理
    if ([keyPath isEqualToString:MKRefreshKeyPathContentSize]) {
        [self scrollViewContentSizeDidChange:change];
    }
    
    // 看不见
    if (self.hidden) return;
    if ([keyPath isEqualToString:MKRefreshKeyPathContentOffset]) {
        [self scrollViewContentOffsetDidChange:change];
    } else if ([keyPath isEqualToString:MKRefreshKeyPathPanState]) {
        [self scrollViewPanStateDidChange:change];
    }
}



/** 初始化 */
- (void)prepare {}

/** 摆放子控件frame */
- (void)placeSubviews {}

/** 当scrollView的contentOffset发生改变的时候调用 */
- (void)scrollViewContentOffsetDidChange:(NSDictionary *)change {}

/** 当scrollView的contentSize发生改变的时候调用 */
- (void)scrollViewContentSizeDidChange:(NSDictionary *)change {}

/** 当scrollView的拖拽状态发生改变的时候调用 */
- (void)scrollViewPanStateDidChange:(NSDictionary *)change {}
@end
